<template>
  <view class="container">
    <view class="header">
      <view class="header-left" @click="goBack">
        <uni-icons type="left" size="28" color="#333"></uni-icons>
      </view>
      <text class="header-title">热门推荐管理</text>
      <view class="header-right">
        <button class="add-btn" type="primary" size="mini" @click="showAddModal">添加</button>
      </view>
    </view>
    
    <view class="content">
      <!-- 热门推荐列表 -->
      <view class="featured-list" v-if="featuredList.length > 0">
        <view v-for="(item, index) in featuredList" :key="item._id" class="featured-item">
          <view class="featured-info">
            <image 
              v-if="item.wallpaper && (item.wallpaper.thumbnail_url || item.wallpaper.file_url)" 
              :src="item.wallpaper.thumbnail_url || item.wallpaper.file_url" 
              mode="aspectFill" 
              class="featured-image" 
            />
            <view class="featured-details">
              <text class="featured-title">{{ item.wallpaper?.title || '未知标题' }}</text>
              <view class="featured-meta">
                <text class="sort-info">排序：{{ item.sort }}</text>
                <text class="create-time">添加时间：{{ formatTime(item.create_time) }}</text>
              </view>
            </view>
          </view>
          
          <view class="featured-actions">
            <uni-easyinput 
              v-model.number="item.sort" 
              type="number" 
              style="width: 80px;" 
              @change="updateSort(item._id, $event)"
            ></uni-easyinput>
            <button class="delete-btn" size="mini" type="warn" @click="removeFeatured(item._id)">移除</button>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-else class="empty-state">
        <uni-icons type="none" size="80" color="#ccc"></uni-icons>
        <text class="empty-text">暂无热门推荐数据</text>
        <button type="primary" @click="showAddModal">添加热门推荐</button>
      </view>
    </view>
    
    <!-- 添加热门推荐弹窗 -->
    <uni-popup ref="addPopup" type="bottom" :animation="true">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">添加热门推荐</text>
          <text class="popup-close" @click="closeAddModal">&times;</text>
        </view>
        
        <view class="popup-body">
          <text class="section-title">选择壁纸</text>
          
          <!-- 搜索框 -->
          <view class="search-box">
            <uni-easyinput 
              v-model="searchKeyword" 
              placeholder="搜索壁纸标题" 
              @input="handleSearch"
              clearable
            ></uni-easyinput>
          </view>
          
          <!-- 壁纸列表 -->
          <scroll-view class="wallpaper-list" scroll-y>
            <view 
              v-for="wallpaper in availableWallpapers" 
              :key="wallpaper._id"
              class="wallpaper-item"
              :class="{ selected: selectedWallpaperIds.includes(wallpaper._id) }"
              @click="toggleWallpaperSelection(wallpaper._id)"
            >
              <image 
                :src="wallpaper.thumbnail_url || wallpaper.file_url" 
                mode="aspectFill" 
                class="wallpaper-image" 
              />
              <text class="wallpaper-title">{{ wallpaper.title }}</text>
              <view v-if="selectedWallpaperIds.includes(wallpaper._id)" class="selected-mark">
                <uni-icons type="success" size="24" color="#07c160"></uni-icons>
              </view>
            </view>
          </scroll-view>
        </view>
        
        <view class="popup-footer">
          <button type="default" @click="closeAddModal">取消</button>
          <button 
            type="primary" 
            :disabled="selectedWallpaperIds.length === 0"
            @click="batchAddFeatured"
          >
            添加 ({{ selectedWallpaperIds.length }})
          </button>
        </view>
      </view>
    </uni-popup>
    
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-overlay">
      <uni-load-more :status="'loading'" />
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const featuredList = ref([]);
const availableWallpapers = ref([]);
const selectedWallpaperIds = ref([]);
const searchKeyword = ref('');
const isLoading = ref(false);
const addPopup = ref(null);

// 加载热门推荐列表
const loadFeaturedList = async () => {
  isLoading.value = true;
  try {
    const res = await uniCloud.callFunction({
      name: 'adminFeaturedManager',
      data: { action: 'getList',uid: uniCloud.getCurrentUserInfo().uid }
    });
    
    if (res.result && res.result.code === 200) {
      featuredList.value = res.result.data || [];
    } else {
      uni.showToast({
        title: res.result?.message || '获取热门推荐失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取热门推荐失败:', error);
    uni.showToast({
      title: '获取热门推荐失败',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 加载可用壁纸（未在热门推荐中的壁纸）
const loadAvailableWallpapers = async (keyword = '') => {
  try {
    // 获取所有壁纸（可根据需要添加分页）
    const res = await uniCloud.callFunction({
      name: 'getList',
      data: {
        page: 1,
        size: 100,
        keyword: keyword
      }
    });
    
    if (res.result && res.result.data) {
      const allWallpapers = res.result.data.list || [];
      
      // 过滤掉已在热门推荐中的壁纸
      const featuredWallpaperIds = featuredList.value.map(item => item.wallpaper_id);
      availableWallpapers.value = allWallpapers.filter(
        wallpaper => !featuredWallpaperIds.includes(wallpaper._id)
      );
    }
  } catch (error) {
    console.error('加载壁纸失败:', error);
  }
};

// 显示添加弹窗
const showAddModal = async () => {
  await loadAvailableWallpapers();
  selectedWallpaperIds.value = [];
  addPopup.value.open();
};

// 关闭添加弹窗
const closeAddModal = () => {
  addPopup.value.close();
  searchKeyword.value = '';
};

// 搜索壁纸
const handleSearch = debounce(async () => {
  await loadAvailableWallpapers(searchKeyword.value);
}, 300);

// 切换壁纸选择状态
const toggleWallpaperSelection = (wallpaperId) => {
  const index = selectedWallpaperIds.value.indexOf(wallpaperId);
  if (index > -1) {
    selectedWallpaperIds.value.splice(index, 1);
  } else {
    selectedWallpaperIds.value.push(wallpaperId);
  }
};

// 批量添加热门推荐
const batchAddFeatured = async () => {
  if (selectedWallpaperIds.value.length === 0) {
    uni.showToast({
      title: '请选择要添加的壁纸',
      icon: 'none'
    });
    return;
  }
  
  isLoading.value = true;
  try {
    const res = await uniCloud.callFunction({
      name: 'adminFeaturedManager',
      data: {
        action: 'batchAdd',
        wallpaper_ids: selectedWallpaperIds.value
      }
    });
    
    if (res.result && res.result.code === 200) {
      uni.showToast({
        title: '添加成功',
        icon: 'success'
      });
      closeAddModal();
      loadFeaturedList();
    } else {
      uni.showToast({
        title: res.result?.message || '添加失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('添加热门推荐失败:', error);
    uni.showToast({
      title: '添加失败',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 更新排序
const updateSort = debounce(async (id, event) => {
  const newSort = Number(event.target.value);
  if (isNaN(newSort)) return;
  
  try {
    const res = await uniCloud.callFunction({
      name: 'adminFeaturedManager',
      data: {
        action: 'updateSort',
        _id: id,
        sort: newSort
      }
    });
    
    if (res.result && res.result.code !== 200) {
      uni.showToast({
        title: res.result?.message || '更新排序失败',
        icon: 'none'
      });
      // 重新加载数据以恢复原排序
      loadFeaturedList();
    }
  } catch (error) {
    console.error('更新排序失败:', error);
    uni.showToast({
      title: '更新排序失败',
      icon: 'none'
    });
    loadFeaturedList();
  }
}, 500);

// 移除热门推荐
const removeFeatured = (id) => {
  uni.showModal({
    title: '提示',
    content: '确定要移除这个热门推荐吗？',
    success: async (res) => {
      if (res.confirm) {
        isLoading.value = true;
        try {
          const result = await uniCloud.callFunction({
            name: 'adminFeaturedManager',
            data: {
              action: 'remove',
              _id: id
            }
          });
          
          if (result.result && result.result.code === 200) {
            uni.showToast({
              title: '移除成功',
              icon: 'success'
            });
            loadFeaturedList();
          } else {
            uni.showToast({
              title: result.result?.message || '移除失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('移除失败:', error);
          uni.showToast({
            title: '移除失败',
            icon: 'none'
          });
        } finally {
          isLoading.value = false;
        }
      }
    }
  });
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 防抖函数
function debounce(fn, delay) {
  let timer = null;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  };
}

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 生命周期
onMounted(() => {
  loadFeaturedList();
});
</script>

<style scoped lang="less">
.container {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 20rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 10;
  
  .header-left,
  .header-right {
    width: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
  
  .add-btn {
    margin: 0;
    padding: 0 20rpx;
    font-size: 28rpx;
  }
}

.content {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
}

.featured-list {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
}

.featured-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
  
  &:last-child {
    border-bottom: none;
  }
  
  .featured-info {
    display: flex;
    align-items: center;
    flex: 1;
    
    .featured-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 8rpx;
    }
    
    .featured-details {
      margin-left: 20rpx;
      flex: 1;
      
      .featured-title {
        font-size: 32rpx;
        color: #333;
        margin-bottom: 10rpx;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .featured-meta {
        display: flex;
        flex-direction: column;
        
        text {
          font-size: 26rpx;
          color: #999;
          margin-bottom: 4rpx;
        }
      }
    }
  }
  
  .featured-actions {
    display: flex;
    align-items: center;
    gap: 16rpx;
    
    .delete-btn {
      margin: 0;
    }
  }
}

.empty-state {
  text-align: center;
  padding: 80rpx 0;
  
  .empty-text {
    display: block;
    margin: 20rpx 0;
    font-size: 32rpx;
    color: #999;
  }
}

/* 弹窗样式 */
.popup-content {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #eee;
    
    .popup-title {
      font-size: 34rpx;
      font-weight: bold;
      color: #333;
    }
    
    .popup-close {
      font-size: 40rpx;
      color: #999;
      padding: 10rpx;
    }
  }
  
  .popup-body {
    padding: 20rpx 30rpx;
    max-height: 50vh;
    
    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .search-box {
      margin-bottom: 20rpx;
    }
    
    .wallpaper-list {
      max-height: 40vh;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 16rpx;
    }
  }
  
  .popup-footer {
    display: flex;
    padding: 20rpx 30rpx;
    border-top: 1rpx solid #eee;
    
    button {
      flex: 1;
      margin: 0 10rpx;
    }
  }
}

.wallpaper-item {
  position: relative;
  padding: 10rpx;
  border: 2rpx solid transparent;
  border-radius: 12rpx;
  
  &.selected {
    border-color: #07c160;
    background-color: #f0f9ff;
  }
  
  .wallpaper-image {
    width: 100%;
    height: 160rpx;
    border-radius: 8rpx;
  }
  
  .wallpaper-title {
    font-size: 26rpx;
    color: #333;
    margin-top: 10rpx;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  
  .selected-mark {
    position: absolute;
    top: 10rpx;
    right: 10rpx;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 50%;
    padding: 4rpx;
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}
</style>